//
//  OAuthViewController.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 16/6/25.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let web_appKey = "3226443203"
    let web_appSecet = "2fb53596126fe23b4b09523f1365bb8a"
    let web_redirectUrl = "http://www.baidu.com"

    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.close))
        
        let web_OAuthUrl = "https://api.weibo.com/oauth2/authorize?client_id=\(web_appKey)&redirect_uri=\(web_redirectUrl)"
        let url = NSURL(string: web_OAuthUrl)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: - 懒加载
    private lazy var webView: UIWebView = {
        let wb = UIWebView()
        wb.delegate = self
        return wb
    }()
    
}

extension OAuthViewController: UIWebViewDelegate
{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString);
        
        
        if !request.URL!.absoluteString!.hasPrefix(web_redirectUrl) {
            // 继续加载
            return true
        }
        
        // 授权 
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr) {
            // 授权成功 取出token
            let code = request.URL?.query?.substringFromIndex(codeStr.endIndex)
            print(code)
            
            // 请求accessToken
            loadAccessToken(code!)
        } else {
            // 授权失败
            close()
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    private func loadAccessToken(code: String) {
        let path = "oauth2/access_token"
        let params = ["client_id":web_appKey,
                      "client_secret":web_appSecet,
                      "grant_type":"authorization_code",
                      "code": code,
                      "redirect_uri":web_redirectUrl]
        
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) in
            
            
            let account = UserAccount(dict: JSON as! [String : AnyObject])
            
            account.loadUserInfo({ (account, error) in
                if account != nil
                {
                    account!.saveAccount()
                    // 去欢迎界面
                    NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: false)
                    return
                }
                SVProgressHUD.showInfoWithStatus("网络不给力")
            })
            
            // 归档模型
//            account.saveAccount()
            
        }) { (_, error) in
                print(error)
        }
        
    }
    
}














